package cn.wolfcode.wolf2w.controller;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/users")
@RestController
public class UserController {
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Autowired
    private IStrategyService strategyService;

    @RequireLogin
    @GetMapping("/get")
    public Object get(String id){
        return userInfoService.get(id);
    }
    @GetMapping("/checkPhone")
    public Object checkPhone(String phone){
        return userInfoService.checkPhone(phone);
    }
    @GetMapping("/sendVerifyCode")
    public Object sendVerifyCode(String phone){
        userInfoService.sendVerifyCode(phone);

        return JsonResult.success();
    }

    @PostMapping("/regist")
    public Object regist(String phone,String nickname,String password,String rpassword,String verifyCode){
        //完成注册功能的实现
        userInfoService.regist( phone, nickname, password, rpassword, verifyCode);
        return JsonResult.success();
    }
    @PostMapping("/login")
    public Object login(String username,String password){
        UserInfo user = userInfoService.login(username, password);
        //使用UUID创建令牌
        String token= UUID.randomUUID().toString().replaceAll("-","");
        //将用户存储到redis中,token拼接为key,user作为值
        userInfoRedisService.setLoginToken(token,user);
        //将token和user存入map集合中
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("user",user);

        //通过JsonResult中的data属性返回给客户端
        return JsonResult.success(map);
    }
    @RequireLogin
    @GetMapping("/currentUser")
    public Object currentUser(HttpServletRequest request){
        //解析请求头中的token信息
        String token = request.getHeader("token");
        //根据token在redis中获取用户对象
        UserInfo user = userInfoRedisService.getUserInfoToToken(token);

        return user;
    }
    @RequireLogin
    @GetMapping("/strategies/favor")
    public Object favor(String sid, String userId) {
      return JsonResult.success(userInfoRedisService.favor(sid,userId));
    }
}
